package security.internal;

import java.util.Iterator;
import java.util.Map;

import kernel.util.StringUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.AccessDecisionManager;
import org.springframework.security.AccessDeniedException;
import org.springframework.security.Authentication;
import org.springframework.security.ConfigAttributeDefinition;

import security.Constants;
import security.SecurityAppUserHolder;
import security.util.AuthenticationUtil;

public class SecurityResourceProcessorImpl implements SecurityResourceProcessor {

    private static final Log logger = LogFactory.getLog(SecurityResourceProcessorImpl.class);

    private SecurityAuthoritiesHolder securityAuthoritiesHolder;

    private AccessDecisionManager accessDecisionManager;

    public boolean isResourceAccessible(String resource) {
        return isResourceAccessible(resource, Constants.RESTYPE_OPERATION);
    }

    public boolean isResourceAccessible(String resource, String type) {
        if (StringUtils.isNullOrEmpty(resource)) {
            return true;
        }
        logger.debug("resource[" + resource + "]");
        Map<String, String> operationAuthorities = securityAuthoritiesHolder.loadAuthorities(type);
        String authorities = null;
        for (Iterator<Map.Entry<String, String>> iter = operationAuthorities.entrySet().iterator(); iter.hasNext();) {
            Map.Entry<String, String> entry = iter.next();
            String operation = entry.getKey();
            if (resource.equals(operation)) {
                authorities = entry.getValue();
                break;
            }

        }
        ConfigAttributeDefinition attr = AuthenticationUtil.getCadByAuthorities(authorities);
        if (attr != null) {
            Authentication authenticated = SecurityAppUserHolder.getAuthentication();
            try {
                accessDecisionManager.decide(authenticated, null, attr);
                return true;
            } catch (AccessDeniedException accessDeniedException) {
                return false;
            }
        }
        return true;

    }


    public void setAccessDecisionManager(AccessDecisionManager accessDecisionManager) {
        this.accessDecisionManager = accessDecisionManager;
    }

	public void setSecurityAuthoritiesHolder(
			SecurityAuthoritiesHolder securityAuthoritiesHolder) {
		this.securityAuthoritiesHolder = securityAuthoritiesHolder;
	}
    
    

}
